<!--设备本地日志-->
<template>
  <div class="device-log">
    <div class="header">
      <span class="back" @click="goBack"><i class="iconfont icon-fanhui" style="font-size: 24px;"></i></span>
      <!-- <div class="title">设备日志 {{ deviceName }}</div> -->
      <div class="title">设备日志</div>
    </div>
    <el-form :inline="true" class="search-form">
      <el-form-item>
        <el-input v-model="deviceId" placeholder="请输入设备ID" clearable @keyup.enter.native="queryList('search')">
          <el-button slot="append" class="search-icon" icon="icon-sousuo" @click="queryList('search')"></el-button>
        </el-input>
      </el-form-item>
      <el-form-item class="date">
        <el-date-picker
          v-model="dateValue"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          class="date-picker"
          :picker-options="pickerOptions"
          clearable
          :style="{ width: '280px' }"
          @blur="isRestart = true">
        </el-date-picker>
        <el-tooltip content="所选时间跨度不能超过30天" placement="top">
          <i class="iconfont icon-wenhao" style="font-size: 22px;"></i>
        </el-tooltip>
      </el-form-item>
      <el-form-item>
        <el-select
          v-model="logType"
          placeholder="请选择"
          clearable
          class="log-type">
          <el-option
            v-for="item in logTypeData"
            :key="item.logType"
            :label="item.logType"
            :value="item.logType">
          </el-option>
        </el-select>
      </el-form-item>
      <div class="search-btn">
        <el-button type="primary" class="button-container" size="14" @click="queryList">搜索</el-button>
        <el-button v-if="activeName === '设备本地日志'" type="primary" class="button-container" size="14" @click="startCollect">启动收集</el-button>
        <el-button v-if="activeName === '设备本地日志'" type="primary" class="button-container" size="14" @click="stopCollect">停止收集</el-button>
      </div>
    </el-form>
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-for="tab in tabs" :key="tab.id" :label="tab.label" :name="tab.name">
        <transition name="fade">
          <el-table
            v-loading="loading"
            :data="tableData"
            style="width: 100%"
            size="medium"
            :header-cell-style="{ background: '#F5F6F7' }"
          >
            <el-table-column label="时间(GMT+8)" width="156px">
              <template slot-scope="scope">
                {{ scope.row.createTime || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="事件" width="100px">
              <template slot-scope="scope">
                {{ scope.row.eventName || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="类型" width="100px">
              <template slot-scope="scope">
                {{ scope.row.logType || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="URL/Topic">
              <template slot-scope="scope">
                <span v-if="scope.row.logType === 'http'">{{ scope.row.httpUrl || "-" }}</span>
                <span v-else>{{ scope.row.topic || "-" }}</span>
              </template>
            </el-table-column>
            <el-table-column label="详情">
              <template slot-scope="scope">
                {{ scope.row.parseData || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="RAW" show-overflow-tooltip>
              <template slot-scope="scope">
                <div v-if="scope.row.logType === 'http'">
                  <div class="cell-ellipsis">requestHeader: {{ scope.row.requestHeader || "-" }}</div>
                  <div class="cell-ellipsis">requestMethod: {{ scope.row.requestMethod || "-" }}</div>
                  <div class="cell-ellipsis">requestParam: {{ scope.row.requestParam || "-" }}</div>
                  <div class="cell-ellipsis">responseParam: {{ scope.row.responseParam.slice(0, 2500) || "-" }}...</div>
                </div>
                <div v-else class="cell-ellipsis">{{ scope.row.payload || "-" }}</div>
                <i v-if="scope.row.logType === 'http'" class="iconfont icon-copy" style="font-size: 24px;" @click="onCopy(scope.row.logType, scope.row.requestHeader, scope.row.requestMethod, scope.row.requestParam, scope.row.responseParam)"></i>
                <i v-else class="iconfont icon-copy" style="font-size: 24px;" @click="onCopy(scope.row.logType, scope.row.payload)"></i>
              </template>
            </el-table-column>
            <el-table-column label="用户" width="100px">
              <template slot-scope="scope">
                {{ scope.row.userName || "-" }}
              </template>
            </el-table-column>
            <el-table-column label="来源" width="70px">
              <template slot-scope="scope">
                {{ scope.row.serverName || "-" }}
              </template>
            </el-table-column>
          </el-table>
        </transition>
      </el-tab-pane>
    </el-tabs>
    <el-pagination
      :current-page="currentPage"
      :page-sizes="[10, 20, 50]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange">
    </el-pagination>
  </div>
</template>
<script>
import { deviceLog, startCollect, stopCollect, getLogTypeList } from '@/api/device/log'
import moment from 'moment'
import ClipboardJS from 'clipboard'
export default {
  name: 'deviceLog',
  data() {
    return {
      deviceId: '', // 设备ID
      deviceName: '', // 设备名称
      logTypeData: [], // 类型数据
      logType: '', // 类型
      dateValue: [moment().subtract(6, 'days').format('YYYY-MM-DD'), moment().subtract(0, 'days').format('YYYY-MM-DD')], // 存储选择的日期范围
      tableData: [], // 列表数据
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页条数
      total: 0, // 列表数据总条数
      loading: false,
      activeName: '全部设备日志',
      tabs: [
        { id: 1, label: '全部设备日志', name: '全部设备日志' },
        { id: 2, label: '设备本地日志', name: '设备本地日志' }
      ]
    }
  },
  computed: {
    pickerOptions() {
      const self = this // 保存组件实例的引用
      return {
        onPick: ({ maxDate, minDate }) => {
          self.isRestart = false
          self.pickerMinDate = minDate ? minDate.getTime() : ''
          if (maxDate) {
            self.pickerMinDate = ''
          }
        },
        disabledDate: (time) => {
          const today = new Date()
          if (self.pickerMinDate !== '') {
            const oneYearInMilliseconds = 30 * 24 * 3600 * 1000 // 考虑闰年的最大天数
            const minTime = self.pickerMinDate - oneYearInMilliseconds
            const maxTime = self.pickerMinDate + oneYearInMilliseconds
            // 禁用超过允许的日期范围和未来的日期
            return time.getTime() < minTime || time.getTime() > maxTime || time.getTime() > today.getTime()
          }
          return time.getTime() > today.getTime() // 禁用未来的日期
        }
      }
    }
  },
  watch: {
    'deviceId'(newValue) {
      sessionStorage.setItem('deviceId', newValue)
    }
  },
  created() {
    if (!(sessionStorage.getItem('deviceId') !== null || undefined)) {
      this.deviceId = this.$route.query.deviceId || ''
    } else {
      this.deviceId = sessionStorage.getItem('deviceId')
    }
    this.deviceName = this.$route.query.deviceName
    this.queryList()
    this.getLogTypeList()
  },
  destroyed() {
    sessionStorage.removeItem('deviceId') // 调用处理离开的方法
  },
  methods: {
    /**
     * 设备日志详情
     * current 当前页码
     * size 每页条数
     */
    queryList(condition) {
      if (!this.deviceId) {
        this.$message.warning("请输入设备ID")
        return
      }
      this.currentPage = condition === 'search' ? 1 : this.currentPage
      this.loading = true
      const params = {
        current: this.currentPage,
        size: this.pageSize,
        deviceId: this.deviceId,
        logType: this.logType,
        startDateTime: moment(this.dateValue[0]).startOf('day').format("YYYY-MM-DD HH:mm:ss"),
        endDateTime: moment(this.dateValue[1]).endOf('day').format("YYYY-MM-DD HH:mm:ss")
      }
      deviceLog(params).then(res => {
        this.tableData = res.data.data.records
        this.total = res.data.data.total
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    getLogTypeList() {
      getLogTypeList().then(res => {
        this.logTypeData = res.data.data
      }).catch(err => {
        this.$message.error(err.message)
      }).finally(() => {
        this.loading = false
      })
    },
    // 启动收集
    startCollect() {
      console.log('启动收集')
      const params = {
        deviceId: this.deviceId
      }
      startCollect(params).then(res => {
        this.$message.success('启动收集成功')
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 停止收集
    stopCollect() {
      console.log('停止收集')
      const params = {
        deviceId: this.deviceId
      }
      stopCollect(params).then(res => {
        this.$message.success('停止收集成功')
      }).catch(err => {
        this.$message.error(err.message)
      })
    },
    // 切换表格tab
    handleClick(tab) {
      this.activeName = tab.name
      this.currentPage = 1
      if (tab.index === '1') {
        this.logType = 'device-log'
      } else {
        this.logType = ''
      }
      this.queryList()
    },
    // 返回设备列表
    goBack() {
      this.$router.push({ path: '/product/device-log/index' })
    },
    // // 重置
    // handleReset() {
    //   this.deviceId = ''
    //   this.dateValue = ''
    //   this.queryList('search')
    // },
    // 复制设备日志详情
    onCopy(type, a, b, c, d) {
      let jsonText = ''
      if (type === 'mqtt') {
        jsonText = a
      } else {
        jsonText = `{"requestHeader":${a},"requestMethod":"${b}","requestParam":${c},"responseParam":${d}}`
      }
      const clipboard = new ClipboardJS(event.target, {
        text: () => jsonText
      })
      clipboard.on('success', () => {
        clipboard.destroy() // 销毁 clipboard 实例
      })
      clipboard.on('error', () => {
        clipboard.destroy() // 销毁 clipboard 实例
      })
      clipboard.onClick(event) // 触发复制操作
      this.$message.success('已复制')
    },
    // 每页条数改变时触发
    handleSizeChange(val) {
      this.pageSize = val
      this.queryList()
    },
    // 当前页变时触发
    handleCurrentChange(val) {
      this.currentPage = val
      this.queryList()
    }
  }
}
</script>
<style lang="scss" scoped>
.device-log {
  height: 100%;

  .header {
    display: flex;
    align-items: center;
    margin-bottom: 17px;

    .title {
      cursor: pointer;
    }

    .title {
      font-size: 18px;
      font-weight: 600;
      color: #252525;
    }
  }

  .search-form {
    margin-bottom: 8px;

    .date {
      margin-left: 24px;

      ::v-deep .el-form-item__content {
        display: flex;
      }

      .date-picker {
        margin-right: 10px;
      }
    }

    .log-type {
      width: 150px;
    }

    .search-btn {
      float: right;

      .button-container {
        margin-left: 25px;
      }
    }

    .search-icon {
      cursor: pointer;
    }
  }
}

.cell-ellipsis {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.icon-copy {
  display: flex;
  flex-direction: row-reverse;
  cursor: pointer;
}

::v-deep .el-range-separator {
  color: #606266;
  padding: 0;
}

::v-deep .el-table .el-loading-spinner {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
</style>
